package org.qianye.soft.stumgr;

import java.awt.BorderLayout;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JToolBar;

import org.qianye.soft.entity.Clazz;
import org.qianye.soft.entity.Student;
import org.qianye.soft.ext.grid.ColumnModel;
import org.qianye.soft.ext.grid.GridPanel;
import org.qianye.soft.ext.toolbar.PagingToolbar;
import org.qianye.soft.repository.StudentRepository;

import com.google.gwt.core.AsyncCallback;
import com.sencha.gxt.data.loader.JDBCProxy;
import com.sencha.gxt.data.shared.loader.PagingLoadConfig;
import com.sencha.gxt.data.shared.loader.PagingLoadResult;
import com.sencha.gxt.data.shared.loader.PagingLoader;

public class StudentView extends JPanel {

	//
	private final StudentRepository repository = StudentRepository.getInstance();

	/**
	 * StudentView
	 */
	public StudentView() {

		init();

	}

	private void init() {

		JToolBar toolBar = new JToolBar("学生管理");
		toolBar.add(new JButton("添加"));

		JDBCProxy<PagingLoadConfig, PagingLoadResult<Student>> proxy = new JDBCProxy<PagingLoadConfig, PagingLoadResult<Student>>() {
			@Override
			public void load(PagingLoadConfig loadConfig, AsyncCallback<PagingLoadResult<Student>> callback) {
				PagingLoadResult<Student> result = null;
				try {
					result = repository.findAll(loadConfig);
				} catch (Exception e) {
					callback.onFailure(e);
					return;
				}
				callback.onSuccess(result);
			}
		};

		final PagingLoader<PagingLoadConfig, PagingLoadResult<Student>> loader = new PagingLoader<PagingLoadConfig, PagingLoadResult<Student>>(proxy);
		PagingToolbar pageBar = new PagingToolbar<Student>(100);
		pageBar.bind(loader);

		ColumnModel<Student> cm = new ColumnModel<Student>();
		cm.addColumn("编号", "id", Integer.class, false);
		cm.addColumn("班级", "clazz", Clazz.class, false);
		cm.addColumn("姓名", "name", String.class, false);
		cm.addColumn("备注", "remark", String.class, false);

		GridPanel<Student> grid = new GridPanel<Student>(cm);
		grid.setLoader(loader);
		grid.setToolbar(toolBar);
		grid.setPagingToolbar(pageBar);

		this.setLayout(new BorderLayout());
		
		add(grid, BorderLayout.CENTER);

		new Thread() {
			@Override
			public void run() {
				loader.load();
			}
		}.start();

	}
}
